package com.thread.thread.AbstractQueuedSynchronizer;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class CaiCaiLock implements Lock, java.io.Serializable {
	private Sync sync=new Sync();
	@Override
	public void lock() {
		sync.acquire(1);
	}

	@Override
	public void lockInterruptibly() throws InterruptedException {

	}

	@Override
	public boolean tryLock() {
		return false;
	}

	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		return false;
	}

	@Override
	public void unlock() {
		sync.release(1);
	}

	@Override
	public Condition newCondition() {
		return null;
	}


	private static class Sync extends AbstractQueuedSynchronizer {

		//独占方式。尝试获取资源，成功则返回true，失败则返回false
		protected boolean tryAcquire(int arg){
			//每一个线程

			int c = getState();
			if(c==0){
				if(compareAndSetState(0,arg)){
					setExclusiveOwnerThread(Thread.currentThread());
					return true;
				}

			}else if(isHeldExclusively()){
				int nextc = c + arg;
				setState(nextc);
			}
			return false;
		}

		//独占方式。尝试释放资源，成功则返回true，失败则返回false
		protected boolean tryRelease(int arg) {
			int c = getState() - arg;
			if (!isHeldExclusively())
				throw new IllegalMonitorStateException();
			boolean free = false;
			if (c == 0) {
				free = true;
				setExclusiveOwnerThread(null);
			}
			setState(c);
			return free;
		}


		@Override
		protected final boolean isHeldExclusively() {
			//检查当前线程是否是所有者
			return getExclusiveOwnerThread() == Thread.currentThread();
		}

	}
}
